import {Component} from '@angular/core';
import {LocalDataSource} from 'ng2-smart-table';
import {UsersService} from '../../../service/users.service';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';

import {EditUserComponent} from './edit-user.component';
import {UserRoleModel} from '../../../models/user-role.model';


@Component({
  selector: 'ngx-user-list',
  templateUrl: './user-list.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
  `],
})
export class UserListComponent {


  settings = {
    hideSubHeader: true,
    mode: 'external',
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    actions: {
      add: false,
    },
    columns: {
      id: {
        title: 'ID',
        type: 'number',
        width: '10%',
      },
      userName: {
        title: 'User Name',
        type: 'string',
        width: '20%',
      },
      email: {
        title: 'E-mail',
        type: 'string',
        width: '30%',
      },
      mobile: {
        title: 'Mobile',
        type: 'string',
        width: '20%',
      },
      createDate: {
        title: 'Join Date',
        type: 'string',
        width: '20%',
      },
    },
  };

  source: LocalDataSource = new LocalDataSource();

  roles: UserRoleModel[] = [];
  constructor(private userService: UsersService, private modalService: NgbModal) {
    this.userService.getUserList().subscribe(res => {
      this.source.load(res);
    });

    this.userService.getRoles().subscribe(res => {
      this.roles = res;
    });

  }

  onDelete(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.userService.removeUserById(event.data.id).subscribe(() => {
        this.source.remove(event.data);
      });
    }
  }


  onEdit(event): void {
    const activeModal = this.modalService.open(EditUserComponent, {size: 'lg', container: 'nb-layout'});
    activeModal.componentInstance.user = event.data;
    activeModal.componentInstance.roles = this.roles;

  }
}
